<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #box {
        width: 100px;
        height: 100px;
        background-color: red;
        cursor: move;
        position: absolute;
    }
</style>

<body>
    <div id="box"></div>
</body>
<script>
    let box = document.querySelector('#box')

    box.onmousedown = function (e) {
        let oEvent = e || event
        //鼠标点击盒子的位置
        let x = oEvent.clientX - box.offsetLeft
        let y = oEvent.clientY - box.offsetTop
        document.onmousemove = function (e) {
            let oEvent = e || event
            //盒子到浏览器的左边距，右边距
            let left = oEvent.clientX - x
            let top = oEvent.clientY - y
            //documentElement.clientWidth 浏览器的宽度
            let maxW = document.documentElement.clientWidth - box.offsetWidth
            let maxH = document.documentElement.clientHeight - box.offsetHeight
            if (left < 0) {
                left = 0
            }
            if (top < 0) {
                top = 0
            }
            if (left > maxW) {
                left = maxW
            }
            if (top > maxH) {
                top = maxH
            }
            box.style.left = left + 'px'
            box.style.top = top + 'px'
        }
    }
    box.onmouseup = function () {
        document.onmousemove = null
    }
</script>

</html>